package ee.tlnk.web;

import java.sql.Date;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ee.tlnk.model.OrderModel;
import ee.tlnk.service.AccountService;
import ee.tlnk.service.OrderService;
import ee.tlnk.service.RoomService;

/**
 * The Class OrderController.
 */
@Controller
public class OrderController {

	/** The order service. */
	@Autowired
	private  OrderService  orderService;

	/** The account service. */
	@Autowired
	private  AccountService  accountService;

	/** The room service. */
	@Autowired
	private  RoomService  roomService;

	/**
	 * List account.
	 *
	 * @param map the map
	 * @return the string
	 */
	@RequestMapping("/order")
	public String listAccount(Map<String, Object> map) {

		map.put("order", new OrderModel());
		map.put("orderList", orderService.listOrders());
		map.put("managerList", accountService.listAccount());
		map.put("roomList", roomService.listRooms());

		return "order";
	}
	
	/**
	 * Validate rooms.
	 *
	 * @param map the map
	 * @return the string
	 */
	@RequestMapping(value = "/validateorder", method = RequestMethod.POST)
	public String validateRooms(Map<String, Object> map, 
			@RequestParam("day") String dayString, 
			@RequestParam("start") String startString, 
			@RequestParam("end") String endString) {
		
		DateFormat timeFormat = new SimpleDateFormat("hh:mm");
		DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
		java.util.Date begin = null;
		java.util.Date end = null;
	    java.util.Date utilDate  =  new java.util.Date();
		try {
			begin = timeFormat.parse(startString);
			end = timeFormat.parse(endString);
			utilDate = dateFormat.parse(dayString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Date sqlDate = new Date(utilDate.getTime());
	    map.put("order", new OrderModel());
		map.put("orderList", orderService.listOrders());
		map.put("managerList", accountService.listAccount());
		map.put("roomList", roomService.listValidatedRooms(sqlDate, (Time)begin, (Time) end));

		return "redirect:/order";
	}


}
